import logging
from course.mongo_models import UserCourseView
from mycelery.main import app

log = logging.getLogger('mycelery')


@app.task
# 存储到MongoDB数据库
def save_to_database(data):
    try:
        user_id = data.get('user_id', None)
        exam_id = data.get('exam_id')
        work_id = data.get('work_id')
        view_time = data.get('view_time', None)
        user_record = UserCourseView(
            user_id=user_id,
            exam_id=exam_id,
            work_id=work_id,
            view_time=view_time
        )
        user_record.save()
        print('用户行为数据已成功保存进数据库')
    except Exception as e:
        print(f"保存失败：{e}")
